import {
    Api,
    getGoodDetail,
    addCartGood,
    getWXPayOptions,
    requestPayment
} from '../../config/api.js';
import {
    WXNavigateTo,
    WXShowToast,
    request, WXshowToast
} from '../../utils/index.js'
var appInst = getApp();

Page({
    data: {
        host: appInst.globalData.host,
        goodid: undefined,
        good: {},
        remaining:0,//剩余羊币
        deduction:0,//抵扣羊币
       subTabs: [{
               id: 0,
               text: '实体卡',
               isActive: true
           },
           {
               id: 1,
               text:'电子卡',
               isActive: false
           }
       ],
    },
    onLoad: function (options) {
        this.setData({
            goodid: options.goodid
        })
        this._getGoodDetail(options.goodid)
    },
    
    onShow: function () {
          this.sleep_coin()
          if (wx.getStorageSync('dzactive')) { //获取选中的地址 如没选中则调用默认收货地址
              let dzactive = wx.getStorageSync('dzactive')
              this.setData({
                  addr: dzactive
              })

              wx.removeStorageSync('dzactive')
          } else { //否则调用默认收货地址
              this._getAddressList()
          }

    },

    _getGoodDetail(goodid) {
        getGoodDetail(goodid).then(res => {
            this.setData({
                good: res
            })
        }).catch(err => {
            console.log(err)
        })
    },


// 添加类名

handleChangeSubTab(e){
    const subtabIndex = e.currentTarget.dataset.subtabIndex

    this.setData({
      subTabs: this.data.subTabs.map(subtab => ({
        ...subtab,
        isActive: subtab.id === subtabIndex
      })),  
    })
},



// 立即领取
  async  _addCart() {
        const {subTabs} = this.data
        if (this.data.goodid === undefined) return
        if(subTabs[0].isActive){//实体卡
             const {data} =await addCartGood(this.data.goodid)
            if(data.code ==2001){
                WXShowToast('加入购物车成功')
                setTimeout(()=>{
                    WXNavigateTo("/pages/cart/cart")
                },500)
            }
        }else{//虚拟卡
            this.orderSeria()
        }
     
    },



//   获取收货地址
async _getAddressList() {
    const {
        data
    } = await request({
        url: Api.getAddressList,
        method: 'POST'
    })
    if(!data.data.length){
        this.setData({
            addr: {}
        })
        return
    }
    data.data.map((item, index) => {
        if (item.state === 1) {
            this.setData({
                addr: item
            })  
        }
    })  
    this.setData({
        addressList: data.data,
    })
},
    
    // 获取羊币
    async sleep_coin() {
        const {
            data
        } = await request({
            url: Api.sheep_coin,
            method: 'POST'
        })

         let sleep_coin = Number(data.data.sleep_coin) / 10
          let  {
              good,
              deduction,
               remaining
          } = this.data
         let   totalMoney = good.price
           if (sleep_coin > totalMoney) {
               deduction = sleep_coin  //抵扣羊币
               remaining = sleep_coin - totalMoney //剩余羊币
               totalMoney = 0.00
           } else {
               totalMoney = totalMoney - sleep_coin
               remaining = 0.00 //剩余羊币
               deduction = sleep_coin //抵扣羊币
           }
           this.setData({
               totalMoney,
               remaining,
               deduction
           })
    },






    // 立即购买

      async orderSeria() {
          const address_id = this.data.addr
          if (!Object.keys(address_id).length) {
              WXshowToast("请选择收货地址")
              setTimeout(()=>{
                  WXNavigateTo("/pages/select_addr/select_addr")
              },500)
              return
          } 
          const openid = wx.getStorageSync("openid") 
          const {
              good,
              totalMoney
          } = this.data
         
         const {  data } = await request({
              url: Api.order,
              data: {
                  goods_id: good.id, //商品Id
                  price: good.price, //商品价格
                  pay_num: 1, //购买数量
                  address_id: address_id.id //收货地址ID
               },
                      method: 'POST'
          })
           if (data.code != 2001) {
                  return
           }
           let  order_no = Object.values(data.data)[0][0].order_sn //订单编号
        //  支付
                     let pay = await getWXPayOptions({
                         money: totalMoney,
                         title: "肉串礼盒",
                         order_no,
                         openid
                     })
                     // 发起微信支付
                     try {
                         const src = await requestPayment(pay.data.data.wx_pub);
                         if (src.errMsg == "requestPayment:ok") {
                             const {
                                 data
                             } = await request({
                                 url: Api.paySleepCoin,
                                 method: 'POST',
                                 data: {
                                     sleep_coin: deduction * 10
                                 }
                             })
                         }
                         WXshowToast("购买成功")
                         setTimeout(()=>{
                            WXNavigateTo('/pages/index/index')
                         },500)
                     } catch (err) {
                         wx.showToast({
                             title: '支付取消',
                             icon: 'none',
                         });
                     }

      },


})